package com.laikan.reader.bookreader.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.DesChapterBuyRequester;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.bookfriend.activity.RechargePage;
import com.laikan.reader.bookreader.engines.EngineOP;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BatchChapterInfo;
import com.laikan.reader.core.bean.ChapterDetailBean;
import com.laikan.reader.core.bean.Des_Chapter_Bean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class DesChapterBuy extends BasicActivity implements OnClickListener {

    private TextView name;
    private LinearLayout linear, long_item, linear_sing_chapter;
    private String bookid;
    private View zhezhao;
    private RelativeLayout chongzhi_show;
    private BaseDataBean<Des_Chapter_Bean> result;
    private Book bookDes;
    private TextView type1_discount, type2_discount, type3_discount, type4_discount;
    private RelativeLayout type1, type2, type3, type4;
    private TextView type1_name, type2_name, type3_name, type4_name;
    private String type = "";
    private String startChapeterID;
    private TextView text_words, text_prices, text_yue, chapter_name_info;
    private boolean notiPage;
    private TextView auto_buy;
    private Drawable img_on, img_off;
    private LinearLayout buy_curr_chapter;
    private int typeRef;
    private int goInType = 3;
    private RelativeLayout top_bg;
    private TextView buy_curr_context;
    private int currChapterStatus = 0;
    private LoadingDialog mloadingDialog;
    private boolean SureFlag = false;

    private TextView beginChapter, endChapter, bug_count, bug_money, account_money;
    private LinearLayout buy_batch_chapter;
    private TextView buy_batch_context;
    private boolean isAutoBuy = true;

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_des_chapter_buy);
        beginChapter = (TextView)findViewById(R.id.beginChapter);
        endChapter = (TextView)findViewById(R.id.endChapter);
        bug_count = (TextView)findViewById(R.id.bug_count);
        bug_money = (TextView)findViewById(R.id.bug_money);
        account_money = (TextView)findViewById(R.id.account_money);
        buy_curr_context = (TextView)findViewById(R.id.buy_curr_context);
        buy_batch_chapter = (LinearLayout)findViewById(R.id.buy_batch_chapter);
        buy_batch_context = (TextView)findViewById(R.id.buy_batch_context);
        auto_buy = (TextView)findViewById(R.id.auto_buy);
        linear_sing_chapter = (LinearLayout)findViewById(R.id.linear_sing_chapter);
        text_words = (TextView)findViewById(R.id.text_words);
        text_prices = (TextView)findViewById(R.id.text_prices);
        text_yue = (TextView)findViewById(R.id.text_yue);
        chapter_name_info = (TextView)findViewById(R.id.chapter_name_info);
        type1_discount = (TextView)findViewById(R.id.type1_discount);
        type2_discount = (TextView)findViewById(R.id.type2_discount);
        type3_discount = (TextView)findViewById(R.id.type3_discount);
        type4_discount = (TextView)findViewById(R.id.type4_discount);
        type1 = (RelativeLayout)findViewById(R.id.type1);
        type2 = (RelativeLayout)findViewById(R.id.type2);
        type3 = (RelativeLayout)findViewById(R.id.type3);
        type4 = (RelativeLayout)findViewById(R.id.type4);
        type1_name = (TextView)findViewById(R.id.type1_name);
        type2_name = (TextView)findViewById(R.id.type2_name);
        type3_name = (TextView)findViewById(R.id.type3_name);
        type4_name = (TextView)findViewById(R.id.type4_name);
        name = (TextView)findViewById(R.id.name);
        linear = (LinearLayout)findViewById(R.id.linear);
        zhezhao = findViewById(R.id.bg_view);
        long_item = (LinearLayout)findViewById(R.id.long_item);
        chongzhi_show = (RelativeLayout)findViewById(R.id.chongzhi_show);
        buy_curr_chapter = (LinearLayout)findViewById(R.id.buy_curr_chapter);
        top_bg = (RelativeLayout)findViewById(R.id.top_bg);
    }

    @Override
    protected void initData() {
        openEventBus();
        mloadingDialog = new LoadingDialog(mContext);
        img_off = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_choice_norma, null);
        img_on = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_choice_selected, null);
        img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
        img_on.setBounds(0, 0, img_on.getMinimumWidth(), img_on.getMinimumHeight());

        Intent intent = getIntent();
        boolean isVis = intent.getBooleanExtra("isVis", false);
        goInType = intent.getIntExtra("goInType", 3);
        typeRef = intent.getIntExtra("typeRef", -1);
        notiPage = intent.getBooleanExtra("notiPage", false);
        if (isVis) {
            linear_sing_chapter.setVisibility(View.VISIBLE);
        }
        bookid = intent.getStringExtra("book_id");
        startChapeterID = intent.getStringExtra("startChapeterID");
        if (TextUtils.isEmpty(startChapeterID)) {
            startChapeterID = "0";
        }
        bookDes = (Book)getIntent().getSerializableExtra("bookDes");
        getDate();
        type1_discount.setRotation(40.0f);
        type2_discount.setRotation(40.0f);
        type3_discount.setRotation(40.0f);
        type4_discount.setRotation(40.0f);
        auto_buy.setCompoundDrawables(img_on, null, null, null); // 设置左图标

        auto_buy.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(mContext, "lk_read_auto_buy");
                if (isAutoBuy) {
                    auto_buy.setCompoundDrawables(img_off, null, null, null);
                    isAutoBuy = false;
                }else {
                    isAutoBuy = true;
                    auto_buy.setCompoundDrawables(img_on, null, null, null);
                }
            }
        });
    }

    @Override
    protected void setListener() {
        top_bg.setOnClickListener(this);
        zhezhao.setOnClickListener(this);
        long_item.setOnClickListener(this);
        type1.setOnClickListener(this);
        type2.setOnClickListener(this);
        type3.setOnClickListener(this);
        type4.setOnClickListener(this);
        buy_curr_chapter.setOnClickListener(this);
        chongzhi_show.setOnClickListener(this);
        buy_batch_chapter.setOnClickListener(this);
    }
    private void showLotChapterContent(int whichNum){
        if(result!=null){
            type = result.getData().getCaseArray().get(whichNum).getCount();
            show(type, result.getData().getCaseArray().get(whichNum).getDisCount());
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.type1:
                showLotChapterContent(0);
                break;
            case R.id.type2:
                showLotChapterContent(1);
                break;
            case R.id.type3:
                showLotChapterContent(2);
                break;
            case R.id.type4:
                showLotChapterContent(3);
                break;
            case R.id.bg_view:
                onBackPressed();
                break;
            case R.id.buy_batch_chapter:
                if (!SureFlag) {
                    buyChapter();
                }else {
                    Intent intent = new Intent(mContext, RechargePage.class);
                    startActivity(intent);
                }
                break;
            case R.id.cancel:
                finish();
                break;
            case R.id.buy_curr_chapter:
                if (currChapterStatus == 1) {
                    EngineOP engineOP = new EngineOP(null);
                    engineOP.chapterBuy(mContext, bookid, startChapeterID, typeRef, goInType, false, isAutoBuy);
                }else if (currChapterStatus == 2) {
                    Intent intent = new Intent(mContext, RechargePage.class);
                    startActivity(intent);
                }

                break;
            case R.id.top_bg:
                onBackPressed();
                break;
            default:
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void show(String str, String distr) {
        DesChapterBuyRequester.getChapterCountData(result.getData().getStartChapterId(), str, bookid, mloadingDialog);
        long_item.setVisibility(View.GONE);
        chongzhi_show.setVisibility(View.VISIBLE);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    public void setData(BaseDataBean<Des_Chapter_Bean> result) {

        linear.setVisibility(View.VISIBLE);

        if (!result.getData().getCaseArray().get(0).isCanUse()) {

            type1.setBackgroundResource(R.drawable.lk_buy_gray);
            type1.setClickable(false);
            type1_name.setTextColor(ContextCompat.getColor(mContext, R.color.C_666666));
        }

        if (!result.getData().getCaseArray().get(1).isCanUse()) {

            type2.setBackgroundResource(R.drawable.lk_buy_gray);
            type2.setClickable(false);
            type2_name.setTextColor(ContextCompat.getColor(mContext, R.color.C_666666));
        }

        if (!result.getData().getCaseArray().get(2).isCanUse()) {

            type3.setBackgroundResource(R.drawable.lk_buy_gray);
            type3.setClickable(false);
            type3_name.setTextColor(ContextCompat.getColor(mContext, R.color.C_666666));
        }

        if (!result.getData().getCaseArray().get(3).isCanUse()) {

            type4.setBackgroundResource(R.drawable.lk_buy_gray);
            type4.setClickable(false);
            type4_name.setTextColor(ContextCompat.getColor(mContext, R.color.C_666666));
        }
        chapter_name_info.setText(result.getData().getStartChapterName().replace(" ", ""));
        type1_discount.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_discount, result.getData().getCaseArray().get(0).getDisCount()));
        type2_discount.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_discount, result.getData().getCaseArray().get(1).getDisCount()));
        type3_discount.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_discount, result.getData().getCaseArray().get(2).getDisCount()));
        type4_discount.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_discount, result.getData().getCaseArray().get(3).getDisCount()));
        type1_name.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_behind_chapter, result.getData().getCaseArray().get(0).getCount()));
        type2_name.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_behind_chapter, result.getData().getCaseArray().get(1).getCount()));
        type3_name.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_behind_chapter, result.getData().getCaseArray().get(2).getCount()));
        type4_name.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_behind_chapter, result.getData().getCaseArray().get(3).getCount()));
        name.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_chapter_buy_from, result.getData().getStartChapterName().replace(" ", "")));
    }

    /**
     * 批量购买信息
     */
    private void showBatchChapterInfo(BaseDataBean<BatchChapterInfo> batchChapterInfo) {
        beginChapter.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapter_beginchapter, batchChapterInfo.getData().getBeginChapter()));
        endChapter.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapter_endchapter, batchChapterInfo.getData().getEndChapter()));
        bug_count.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapter_buycount, batchChapterInfo.getData().getChapterCount()));
        bug_money.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapter_buy_money, batchChapterInfo.getData().getDiscountMoney(), batchChapterInfo.getData().getRealMoney()));
        int money = (int)(Float.parseFloat(batchChapterInfo.getData().getUserMoney()) * 100);
        account_money.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapter_account_money, money, batchChapterInfo.getData().getUserTicket()));
        if (batchChapterInfo.getError_no().equals("602")) {
            buy_batch_context.setText(R.string.deschapter_yuebuzu);
            SureFlag = true;
        }else {
            buy_batch_context.setText(R.string.deschapter_lijibuy);
            SureFlag = false;
        }
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        switch (event.getEventID()) {
            case LaiKanEvent.EVENT_ID_GET_PREPAY_INFO:
                BaseDataBean<BatchChapterInfo> infos = (BaseDataBean<BatchChapterInfo>)event.getElves();
                showBatchChapterInfo(infos);
                break;
            default:
                break;
        }
    }

    /**
     * 从网络获取数据
     */
    private void getDate() {
        mloadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("bookId", bookid);
        map.put("startChapeterID", startChapeterID);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mloadingDialog.dismiss();
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<Des_Chapter_Bean>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                }catch (Exception e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    return;
                }
                if (result.getResult().equals("1")) {
                    SPUtil.putBoolean("login_laikan_setting", true);
                    if (Integer.valueOf(result.getData().getChapterCount()) == 0) {
                        ToastMgr.showShortToast(R.string.deschapterbuy_none_chapter_can_buy);
                        finish();
                    }else {
                        if (notiPage) {
                            getData11();
                        }
                        setData(result);
                    }

                }else if (result.getResult().equals("0")) {
                    ToastMgr.showShortToast(result.getError_msg());
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
                if ("604".equals(result.getError_no())) {
                    ToastMgr.showShortToast(result.getError_msg());
                }
                if ("102".equals(result.getError_no())) {
                    ToastMgr.showShortToast(result.getError_msg());
                    finish();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mloadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                finish();
                KLog.e("网络不给力，请重试。13");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_deschapterbuy);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_deschapterbuy, map, null, null, requestListener);
    }

    /**
     * 批量购买
     */
    private void buyChapter() {

        mloadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("bookId", bookid);
        map.put("startChapeterID", startChapeterID);
        map.put("count", type);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mloadingDialog.dismiss();
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<Des_Chapter_Bean>>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                }catch (Exception e) {
                    // TODO: handle exception
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);

                    e.printStackTrace();
                    return;
                }
                KLog.e("-------------------test   errorNo:" + result.getError_no());
                String errorNo = result.getError_no();
                String errorMsg = result.getError_msg();
                if (result.getResult().equals(Constants.RESULT_OK)) {
                    DBBook.getInstance().insertBook(bookDes);
                    ToastMgr.showShortToast(R.string.deschapterbuy_buy_success);
                    if (typeRef != -1) {
                        SPUtil.putBoolean("IsRefer", true);
                        SPUtil.putInt("typeRef", typeRef);
                    }
                    SPUtil.putInt(bookid + startChapeterID + "buyback", goInType);
                    finish();
                }
                if (!(Constants.RESULT_BALANCE_NOT_ENOUGH.equals(errorNo) || Constants.RESULT_TICKET_NOT_ENOUGH.equals(errorNo))) {
                    ToastMgr.showShortToast(errorMsg);
                    finish();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mloadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。13");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_deschapterbuy_detail);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_deschapterbuy_detail, map, null, null, requestListener);
    }

    /**
     * 是否充值
     */

    private void chongZhi() {
        new AlertDialog.Builder(mContext).setTitle(R.string.reward_enter_recharge_page).setNegativeButton(R.string.reder_detail_buy, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(mContext, RechargePage.class);
                startActivity(intent);
            }
        }).setPositiveButton(R.string.dialog_btn_cancle, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();

            }
        }).show();
    }

    @Override
    protected void onDestroy() {

        SPUtil.putBoolean("DoubleVis", false);
        overridePendingTransition(R.anim.close, 0);
        super.onDestroy();

    }

    /**
     * 访问网络 获取章节数据
     */
    private void getData11() {
        HashMap<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    ParseJosn(httpResponse.responseContent);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_data_load_failed);
            }

            @Override
            public void onFinish() {

            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_detail + bookid + "_" + startChapeterID);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_book_detail + bookid + "_" + startChapeterID, map, null, null, requestListener);

    }

    private void ParseJosn(final String json) {
        KLog.json(json);

        BaseDataBean<ChapterDetailBean> result;
        Gson gson = new Gson();
        Type type = new TypeToken<BaseDataBean<ChapterDetailBean>>() {}.getType();
        try {
            result = gson.fromJson(json, type);
            KLog.json(json);
            if (result != null) {
                if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {

                    // 未获取到章节内容
                    if (Constants.RESULT_NEED_BUY.equals(result.getError_no())) {// 需要购买:601
                        buy_curr_context.setText(R.string.deschapterbuy_buy_immediately);
                        currChapterStatus = 1;
                    }else if (Constants.RESULT_BALANCE_NOT_ENOUGH.equals(result.getError_no())) {// 余额不足:602
                        currChapterStatus = 2;
                        buy_curr_context.setText(R.string.deschapterbuy_need_recharge);
                    }
                    if (Constants.RESULT_NEED_BUY.equals(result.getError_no()) || Constants.RESULT_BALANCE_NOT_ENOUGH.equals(result.getError_no())) {
                        text_words.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_word_count, result.getData().getWords()));
                        text_prices.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_K_count, result.getData().getPrice()));
                        text_yue.setText(DeviceUtil.getHtmlFormatedString(mContext, R.string.deschapterbuy_K_balance, result.getData().getBalance(), result.getData().getMtTicket()));
                    }
                }
            }else {
                ToastMgr.showShortToast(R.string.laikan_data_load_failed);
            }

        }catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.close);
    }
}
